﻿using FastReport;
using FastReport.Data;
using FastReport.Web;
using FastReport.Web.Handlers;
using LanDBom.Models;
using LanDBom.Models.Admin;
using Microsoft.Ajax.Utilities;
using Microsoft.Office.Interop.Excel;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Windows.Forms;
using static Microsoft.WindowsAPICodePack.Shell.PropertySystem.SystemProperties.System;

namespace LanDBom.Controllers
{
    public class AdminController : Controller
    {
        Admin__Find A_find = new Admin__Find();
        Admin__Append A_append = new Admin__Append();
        LDbaseEntities db = new LDbaseEntities();
        // GET: Admin
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Employee_management(int id = -99, string name = null, string standing = null, int state = 0, string HUNF = "")
        {
            ViewBag.List_employee = A_find.find_Employee();
            ViewBag.List_bu = db.F_BuMen.ToList();
            ViewBag.List_zhi = db.F_Shen.ToList();
            if (state == 1)
            {
                var listinf = A_find.find_Employee(name, standing, id);
                var list = from a in listinf
                           select new
                           {
                               a.DE_ID,
                               a.DE_nae,
                               a.DE_phone,
                               a.DE_quan,
                               a.DE_Pass,
                               FName_B = a.DE_bumeng == null ? "0" : (a.F_BuMen == null ? "0" : a.F_BuMen.FName),
                               FName_S = a.DE_shenfen == null ? "0" : (a.F_Shen == null ? "0" : a.F_Shen.FName),
                               a.DE_email
                           };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);

                return Content(jsongStr, "application/json");
            }
            if (state == 2)
            {
                var listinf = db.F_Shen.Where(x => x.FBuMen == id).ToList();
                var list = from a in listinf
                           select new { a.FID, a.FName };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);

                return Content(jsongStr, "application/json");
            }
            if (state == 3)
            {
                var JNHM = HUNF == "" ? 0 : int.Parse(HUNF);
                var shun = db.Dengli.Where(s => s.DE_ID == JNHM).ToList();
                var list = from a in shun
                           select new
                           {
                               a.DE_ID,
                               a.DE_bumeng,
                               a.DE_dizhi,
                               a.DE_nae,
                               a.DE_email,
                               a.DE_Pass,
                               a.DE_phone,
                               a.DE_shenfen,
                               a.DE_quan
                           };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            return View();
        }
        /// <summary>
        /// 添加新员工
        /// </summary>
        /// <returns></returns>
        public JsonResult Add_employee(Dengli DL)
        {
            var shun = "";
            try
            {
                int rows = A_append.AddEmployee(DL);
                string index = "";
                 shun = rows > 0 ? DL.DE_ID > 0 ? "修改成功":"成功添加" + rows + "名新员工": "添加失败";
               
            }
            catch (Exception ex)
            {
                shun=ex.Message;
            }
            return Json(shun);
        }
        /// <summary>
        /// Purchasing_Authority
        /// </summary>
        /// <returns></returns>
        public JsonResult Deletion_of_employee(Dengli dl)
        {
            int rows = dl.DE_ID;
            var denamnr = db.Dengli.FirstOrDefault(s => s.DE_ID == rows);
            denamnr.DE_zhuang = dl.DE_zhuang;
            db.Entry(denamnr).State = EntityState.Modified;
            int sun = db.SaveChanges();
            string index = "成功删除" + sun + "名新员工";
            return Json(index);
        }
        /// <summary>
        /// 修改员工信息
        /// </summary>
        /// <returns></returns>
        public JsonResult Modify_employee_information(Dengli dl)
        {
            LDbaseEntities db = new LDbaseEntities();

            int rows = dl.DE_ID;
            var denamnr = db.Dengli.FirstOrDefault(s => s.DE_ID == rows);
            denamnr.DE_nae = dl.DE_nae;
            denamnr.DE_Pass = dl.DE_Pass;
            denamnr.DE_quan = dl.DE_quan;
            denamnr.DE_phone = dl.DE_phone;
            db.Entry(denamnr).State = EntityState.Modified;
            int sun = db.SaveChanges();
            string index = "成功修改" + sun + "名新员工";
            return Json(index);
        }

        public ActionResult Print(string Appbian = "", string path = "")
        {
            try
            {
                //数据源
                path = Server.MapPath(path);
                var webReport = new WebReport();
                webReport.LoadFromFile(path);
                //webReport.RegisterData(Appbian, "ksnfjidn");
                //webReport.Load(path);//打开文件/*
                ////绑定数据源
                webReport.Report.SetParameterValue("ksnfjidn", Appbian);//替换fastreport参数的值--
                webReport.Width = 1000;
                webReport.Height = 1000;
                ViewBag.WebReport = webReport.GetHtml();
            }
            catch (Exception ex )
            {
                ViewBag.WebReport = ex.Message;
            }
            return View();
        }
        public ActionResult shenpiView(string Namse = "", int stse = 0, string bian = "", string shunf = "", string zhunag = "")
        {
            var sjindf = db.shenpingliu.Where(x => x.Fzhuang != "结束" && x.Fzhuang != "驳回").ToList();

            sjindf = sjindf.Where(s => s.FFirst == Namse || s.FTwo == Namse || s.FThree == Namse).ToList();
            if (stse == 1)
            {
                var temp = new List<shenpingliu>();
                foreach (var item in sjindf)
                {
                    var HSUnf = db.Applications.Where(s => s.AP_bian == item.FJINF).FirstOrDefault();
                    item.FFS = HSUnf == null ? "" : HSUnf.App_Kehu;
                    item.FFive = HSUnf == null ? "" : HSUnf.APP_name;
                    temp.Add(item);
                }
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(temp, settings);
                return Content(jsongStr, "application/json");
            }
            if (stse == 2)
            {
                var app = db.Applications.ToList();
                var temp = from a in sjindf
                           join b in app on a.FJINF equals b.AP_bian into c
                           from d in c.DefaultIfEmpty()
                           select new { App_Kehu = d.App_Kehu, APP_name = d.APP_name, a.FID, a.FJINF, a.FMIao, a.FQsj, a.FShenR, a.FFZ, a.FTZ, a.Fzhuang, a.FTwo, a.FFirst };
                if (bian != "")
                {
                    temp = temp.Where(s => s.FJINF.Contains(bian)).ToList();
                }
                if (shunf != "")
                {
                    temp = temp.Where(s => s.FShenR.Contains(shunf)).ToList();
                }
                if (zhunag != "")
                {
                    temp = temp.Where(s => s.FMIao == zhunag).ToList();
                }

                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(temp, settings);

                return Content(jsongStr, "application/json");
            }
            return View();
        }
        public ActionResult SJINFlp(Sheji fordat, int stanf = 0)
        {
            if (stanf == 1)
            {
                string mess = "";
                if (fordat != null)
                {
                    db.Sheji.Add(fordat);
                    int sjinf = db.SaveChanges();
                    mess = sjinf == 1 ? "添加成功" : "添加失败";
                }
                else
                {
                    mess = "添加失败";

                }
                return Content(mess);
            }

            return View();
        }
        public ActionResult Shtuzhi(HttpPostedFileBase file)
        {
            var path = "";
            try
            {
                //解决方案 先保存到服务器后使用
                if (file != null && file.ContentLength > 0)
                {
                    // 指定保存文件的路径（服务器上的实际路径）  
                    path = Server.MapPath("~/Baobiao/");
                    // 确保目录存在  
                    Directory.CreateDirectory(path);

                    // 生成唯一的文件名（这里只是简单示例，你可能需要更复杂的唯一性逻辑）  
                    string fileName = Path.GetFileNameWithoutExtension(file.FileName) + "_" + Guid.NewGuid() + Path.GetExtension(file.FileName);
                    string lujing = "~/Baobiao/" + fileName;
                    // 保存文件到服务器  
                    string filePath = Path.Combine(path, fileName);
                    file.SaveAs(filePath);//真实路径
                    // 返回消息  
                    return Json(lujing);
                }
            }
            catch (Exception)
            {
                // 返回失败消息  
                return Json(new { success = false, message = "没有文件被上传或者文件大小为0." });
            }
            return View();
        }

        public ActionResult Purchasing_Authority(buty2 buty, int state = 0, int id = 0)
        {
            var temp2 = db.buty3.ToList();
            ViewBag.temp2 = temp2;
            if (state == 1)
            {
                var temp = db.Dengli.Where(x => x.DE_bumeng == 3).ToList();
                var index = from x in temp
                            select new { x.DE_ID, x.DE_nae, FName = x.F_BuMen.FName, x.DE_quan };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(index, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 2)
            {
                var temp = db.duty.Where(x => x.dl_id == id).ToList();
                var index = from x in temp
                            select new { dl_id = x.Dengli.DE_nae, x.du_name, x.du_id };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(index, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 3)
            {
                duty duty2 = db.duty.Where(x => x.du_id == id).FirstOrDefault();
                db.duty.Remove(duty2);
                int num = db.SaveChanges();
                if (num > 0)
                {
                    return Content("删除成功");

                }
                else
                {
                    return Content("删除失败");
                }
            }
            else if (state == 4)
            {
                var temp = db.buty2.Where(x => x.zl2_id == id).ToList();
                var index = from x in temp
                            select new { x.zl_name };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(index, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 5)
            {
                int num = 0;
                var shunf = buty.zl_name;
                var AA = db.buty2.Where(g => g.zl_name == shunf).FirstOrDefault();
                if (AA == null)
                {
                    var sjj = AA.zl_name;
                    var BB = db.duty.Where(s => s.du_name == sjj).ToList();
                    if (BB.Count > 0)
                    {
                        foreach (var item in BB)
                        {
                            db.duty.Remove(item); db.SaveChanges();
                        }
                    }
                    db.buty2.Add(buty);
                    num = db.SaveChanges();

                }
                else
                {
                    num = 2;
                }
                string message = num == 0 ? "添加失败" : num == 2 ? "二级分类名已存在" : "添加成功";
                return Content(message);
            }
            else if (state == 6)
            {
                var temp = db.buty2.ToList();
                var list = from x in temp select new { x.zl_name, x.zl2_id, x.zl_id };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 7)
            {
                int num = 0;
                var AA = db.buty2.Where(g => g.zl_id == id).FirstOrDefault();
                if (AA != null)
                {
                    db.buty2.Remove(AA);
                    num = db.SaveChanges();
                }
                else
                {
                    num = 2;
                }
                string message = num == 0 ? "删除失败" : num == 2 ? "二级分类名不存在" : "删除成功";
                return Content(message);
            }
            else if (state==8)
            {
                var temp = db.Dengli.Where(x => x.DE_bumeng == 3).ToList();
                var KMJ = db.duty.ToList();
                var shun= from x in KMJ join d in temp on x.dl_id equals d.DE_ID select new { x.du_name,d.DE_nae,d.DE_quan,F_BuMen=d.F_BuMen.FName,d.DE_ID };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(shun, settings);
                return Content(jsongStr, "application/json");
            }
            return View();
        }

        public ActionResult AddNdardo_CP(List<duty> duties)
        {
            int index = 0;
            foreach (duty a in duties)
            {
                using (LDbaseEntities db = new LDbaseEntities())
                {
                    if (duties == null)
                    {
                        duties = new List<duty>();
                    }
                    duty lan = new duty()
                    {
                        dl_id = a.dl_id,
                        du_name = a.du_name,
                    };
                    db.duty.Add(lan);
                    index += db.SaveChanges();
                }

            }
            string all = "新增:" + index + "条";
            return Json(all);

        }
        public ActionResult AddNdardo_(List<buty2> duties)
        {
            int index = 0;
            foreach (buty2 a in duties)
            {
                var shunf = a.zl_name;
                var AA = db.buty2.Where(g => g.zl_name == shunf).FirstOrDefault();
                if (AA == null)
                {
                    db.buty2.Add(a);
                    index += db.SaveChanges();
                }
            }
            string all = "新增:" + index + "条";
            return Json(all);

        }
        public ActionResult Material_Classification(int state = 0)
        {
            var temp2 = db.buty3.ToList();
            ViewBag.temp2 = temp2;
            if (state == 1)
            {
                var temp = db.buty2.ToList();
                var index = from x in temp
                            select new { zl2_i = x.buty3.zl2_name, x.zl_name, x.zl_id, x.zl2_id };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(index, settings);
                return Content(jsongStr, "application/json");
            }
            return View();
        }
    }
}